// Scintilla source code edit control
/** @file LexLSL.cxx
 ** Lexer for Linden Scripting Language LSL
 **/
// This is the C++ lexer modified for LSL by Jason Keeslar <jasonkeeslar@gmail.com>
// All the real work was done by the author listed below.
// Pretty much just removed a lot of stuff, doc comment, multi line comments, etc.
// Changed the keyword lists to allow all styles 0-8

// Copyright 1998-2005 by Neil Hodgson <neilh@scintilla.org>
// The License.txt file describes the conditions under which this software may be distributed.

#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <stdio.h>
#include <stdarg.h>

#include "Platform.h"

#include "PropSet.h"
#include "Accessor.h"
#include "StyleContext.h"
#include "KeyWords.h"
#include "Scintilla.h"
#include "SciLexer.h"
#include "CharacterSet.h"

#ifdef SCI_NAMESPACE
using namespace Scintilla;
#endif


static void ColouriseLslDoc(unsigned int startPos, int length, int initStyle, WordList *keywordlists[], Accessor &styler) {

	WordList &keywords = *keywordlists[0];
	WordList &keywords2 = *keywordlists[1];
	WordList &keywords3 = *keywordlists[2];
	WordList &keywords4 = *keywordlists[3];
	WordList &keywords5 = *keywordlists[4];
	WordList &keywords6 = *keywordlists[5];
	WordList &keywords7 = *keywordlists[6];
	WordList &keywords8 = *keywordlists[7];
	WordList &keywords9 = *keywordlists[8];

	bool stylingWithinPreprocessor = styler.GetPropertyInt("styling.within.preprocessor") != 0;
	CharacterSet setOKBeforeRE(CharacterSet::setNone, "([{=,:;!%^&*|?~+-");
	CharacterSet setCouldBePostOp(CharacterSet::setNone, "+-");
	CharacterSet setDoxygen(CharacterSet::setLower, "$@\\&<>#{}[]");
	CharacterSet setWordStart(CharacterSet::setAlpha, "_", 0x80, true);
	CharacterSet setWord(CharacterSet::setAlphaNum, "._", 0x80, true);

	int visibleChars = 0;
	bool continuationLine = false;

	if (initStyle == SCE_LSL_PREPROCESSOR) {
		// Set continuationLine if last character of previous line is '\'
		int lineCurrent = styler.GetLine(startPos);
		if (lineCurrent > 0) {
			int chBack = styler.SafeGetCharAt(startPos-1, 0);
			int chBack2 = styler.SafeGetCharAt(startPos-2, 0);
			int lineEndChar = '!';
			if (chBack2 == '\r' && chBack == '\n') {
				lineEndChar = styler.SafeGetCharAt(startPos-3, 0);
			} else if (chBack == '\n' || chBack == '\r') {
				lineEndChar = chBack2;
			}
			continuationLine = lineEndChar == '\\';
		}
	}

	StyleContext sc(startPos, length, initStyle, styler);

	for (; sc.More(); sc.Forward()) {

		if (sc.atLineStart) {
			if (sc.state == SCE_LSL_STRING) {
				// Prevent SCE_LSL_STRINGEOL from leaking back to previous line which
				// ends with a line continuation by locking in the state upto this position.
				sc.SetState(SCE_LSL_STRING);
			}
			// Reset states to begining of colourise so no surprises
			// if different sets of lines lexed.
			visibleChars = 0;
		}

		// Handle line continuation generically.
		if (sc.ch == '\\') {
			if (sc.chNext == '\n' || sc.chNext == '\r') {
				sc.Forward();
				if (sc.ch == '\r' && sc.chNext == '\n') {
					sc.Forward();
				}
				continuationLine = true;
				continue;
			}
		}

		// Determine if the current state should terminate.
			if(sc.state == SCE_LSL_OPERATOR){
				sc.SetState(SCE_LSL_DEFAULT);
			}
			else if(sc.state== SCE_LSL_NUMBER){
				// We accept almost anything because of hex. and number suffixes
				if (!setWord.Contains(sc.ch)) {
					sc.SetState(SCE_LSL_DEFAULT);
				}
			}
			else if(sc.state == SCE_LSL_IDENTIFIER ){
				if (!setWord.Contains(sc.ch) || (sc.ch == '.')) {
					char s[1000];
					sc.GetCurrent(s, sizeof(s));
					if (keywords.InList(s)) {
						sc.ChangeState(SCE_LSL_WORD);
					} else if (keywords2.InList(s)) {
						sc.ChangeState(SCE_LSL_WORD2);
					} else if (keywords3.InList(s)) {
						sc.ChangeState(SCE_LSL_WORD3);
					} else if (keywords4.InList(s)) {
						sc.ChangeState(SCE_LSL_WORD4);
					} else if (keywords5.InList(s)) {
						sc.ChangeState(SCE_LSL_WORD5);
					} else if (keywords6.InList(s)) {
						sc.ChangeState(SCE_LSL_WORD6);
					} else if (keywords7.InList(s)) {
						sc.ChangeState(SCE_LSL_WORD7);
					} else if (keywords8.InList(s)) {
						sc.ChangeState(SCE_LSL_WORD8);
					} else if (keywords9.InList(s)) {
						sc.ChangeState(SCE_LSL_WORD9);
					}
					sc.SetState(SCE_LSL_DEFAULT);
				}
			}
			else if(sc.state == SCE_LSL_PREPROCESSOR){
				if (sc.atLineStart && !continuationLine) {
					sc.SetState(SCE_LSL_DEFAULT);
				} else if (stylingWithinPreprocessor) {
					if (IsASpace(sc.ch)) {
						sc.SetState(SCE_LSL_DEFAULT);
					}
				} else {
					if (sc.Match('/', '*') || sc.Match('/', '/')) {
						sc.SetState(SCE_LSL_DEFAULT);
					}
				}
			}
			else if(sc.state == SCE_LSL_COMMENT){
				if (sc.atLineStart) {
					sc.SetState(SCE_LSL_DEFAULT);
				}
			}
			else if(sc.state == SCE_LSL_STRING){
				if (sc.atLineEnd) {
					sc.ChangeState(SCE_LSL_STRINGEOL);
				} else if (sc.ch == '\\') {
					if (sc.chNext == '\"' || sc.chNext == '\'' || sc.chNext == '\\') {
						sc.Forward();
					}
				} else if (sc.ch == '\"') {
					sc.ForwardSetState(SCE_LSL_DEFAULT);
				}
			}
			else if(sc.state == SCE_LSL_STRINGEOL){
				if (sc.atLineStart) {
					sc.SetState(SCE_LSL_DEFAULT);
				}
			}

		// Determine if a new state should be entered.
		if (sc.state == SCE_LSL_DEFAULT) {
			if (IsADigit(sc.ch) || (sc.ch == '.' && IsADigit(sc.chNext))) { // LSL_NUMBER
				sc.SetState(SCE_LSL_NUMBER);
			} else if (setWordStart.Contains(sc.ch)) { // SCE_LSL_IDENTIFIER
				sc.SetState(SCE_LSL_IDENTIFIER);
			} else if (sc.Match('/', '/')) { // SCE_LSL_COMMENT
				sc.SetState(SCE_LSL_COMMENT);
			} else if (sc.ch == '\"') { // SCE_LSL_STRING
				sc.SetState(SCE_LSL_STRING);
			} else if (sc.ch == '#' && visibleChars == 0) { // SCE_LSL_PREPROCESSOR
				// Preprocessor commands are alone on their line
				sc.SetState(SCE_LSL_PREPROCESSOR);
				// Skip whitespace between # and preprocessor word
				do {
					sc.Forward();
				} while ((sc.ch == ' ' || sc.ch == '\t') && sc.More());
				if (sc.atLineEnd) {
					sc.SetState(SCE_LSL_DEFAULT);
				}
			} else if (isoperator(static_cast<char>(sc.ch))) {
				sc.SetState(SCE_LSL_OPERATOR);
			}
		}
		continuationLine = false;
	}
	sc.Complete();
}

// Store both the current line's fold level and the next lines in the
// level store to make it easy to pick up with each increment
// and to make it possible to fiddle the current level for "} else {".
static void FoldLslDoc(unsigned int startPos, int length, int initStyle, WordList *[], Accessor &styler) {
	bool foldComment = styler.GetPropertyInt("fold.comment") != 0;
	bool foldPreprocessor = styler.GetPropertyInt("fold.preprocessor") != 0;
	bool foldCompact = styler.GetPropertyInt("fold.compact", 1) != 0;
	bool foldAtElse = styler.GetPropertyInt("fold.at.else", 0) != 0;
	unsigned int endPos = startPos + length;
	int visibleChars = 0;
	int lineCurrent = styler.GetLine(startPos);
	int levelCurrent = SC_FOLDLEVELBASE;
	if (lineCurrent > 0)
		levelCurrent = styler.LevelAt(lineCurrent-1) >> 16;
	int levelMinCurrent = levelCurrent;
	int levelNext = levelCurrent;
	char chNext = styler[startPos];
	int styleNext = styler.StyleAt(startPos);
	int style = initStyle;
	for (unsigned int i = startPos; i < endPos; i++) {
		char ch = chNext;
		chNext = styler.SafeGetCharAt(i + 1);
		style = styleNext;
		styleNext = styler.StyleAt(i + 1);
		bool atEOL = (ch == '\r' && chNext != '\n') || (ch == '\n');
		if (foldComment && (style == SCE_LSL_COMMENT)) {
			if ((ch == '/') && (chNext == '/')) {
				char chNext2 = styler.SafeGetCharAt(i + 2);
				if (chNext2 == '{') {
					levelNext++;
				} else if (chNext2 == '}') {
					levelNext--;
				}
			}
		}
		if (foldPreprocessor && (style == SCE_LSL_PREPROCESSOR)) {
			if (ch == '#') {
				unsigned int j = i + 1;
				while ((j < endPos) && IsASpaceOrTab(styler.SafeGetCharAt(j))) {
					j++;
				}
				if (styler.Match(j, "region") || styler.Match(j, "if")) {
					levelNext++;
				} else if (styler.Match(j, "end")) {
					levelNext--;
				}
			}
		}
		if (style == SCE_LSL_OPERATOR) {
			if (ch == '{') {
				// Measure the minimum before a '{' to allow
				// folding on "} else {"
				if (levelMinCurrent > levelNext) {
					levelMinCurrent = levelNext;
				}
				levelNext++;
			} else if (ch == '}') {
				levelNext--;
			}
		}
		if (atEOL) {
			int levelUse = levelCurrent;
			if (foldAtElse) {
				levelUse = levelMinCurrent;
			}
			int lev = levelUse | levelNext << 16;
			if (visibleChars == 0 && foldCompact)
				lev |= SC_FOLDLEVELWHITEFLAG;
			if (levelUse < levelNext)
				lev |= SC_FOLDLEVELHEADERFLAG;
			if (lev != styler.LevelAt(lineCurrent)) {
				styler.SetLevel(lineCurrent, lev);
			}
			lineCurrent++;
			levelCurrent = levelNext;
			levelMinCurrent = levelCurrent;
			visibleChars = 0;
		}
		if (!IsASpace(ch)){
			visibleChars++;
		}
	}
}

static const char * const lslWordLists[] = {
            "States and Functions",
            "Identifiers",
            "Keywords",
            "Events",
            "Constants",
			"Unused",
			"Unused",
			"Unused",
			"Unused",
            0,
        };

static void ColouriseLsl(unsigned int startPos, int length, int initStyle, WordList *keywordlists[], Accessor &styler) {
	ColouriseLslDoc(startPos, length, initStyle, keywordlists, styler);
}

LexerModule lmLSL(SCLEX_LSL, ColouriseLsl, "lsl", FoldLslDoc, lslWordLists);
